package cn.fastloader.web.service.impl;

import cn.fastloader.util.SftpUtils;
import cn.fastloader.web.service.SftpFileService;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Vector;

/**
 * @description: SFTP文件服务实现类
 * @author: wzg
 * @create: 2021-09-17
 **/

@Slf4j
@Service
public class SftpFileServiceImpl implements SftpFileService {


    @Autowired
    private SftpUtils sftpUtils;


    /**
     *
     * @param sftpPath  sftp文件目录
     * @param targetPath  目标存放文件目录
     * @param sftpFileName  sftp文件名
     * @param targetFileName  下载保存文件名
     * @return
     * @throws Exception
     */
    @Override
    public boolean downloadFile(String sftpPath, String targetPath,String sftpFileName,String targetFileName) throws Exception {

        long start = System.currentTimeMillis();
        // 开启sftp连接
        ChannelSftp sftp = sftpUtils.createSftp();
        OutputStream outputStream = null;
        try {


            boolean isExist = isDirExist(sftpPath,sftp);

            // sftp文件夹存在
            if(isExist){
                // 进入sftp文件目录
                sftp.cd(sftpPath);
                log.info("Change path to {}", sftpPath);

                File file = new File(targetPath+targetFileName);

                // 如果文件已经存在，删除
                if (file.exists()) {
                    file.delete();
                }

                // 创建文件夹
                new File(targetPath).mkdirs();
                // 创建文件
                file.createNewFile();

                outputStream = new FileOutputStream(file);

                if(sftpFileName.equals("")){
                    Vector fileList = sftp.ls(sftpPath);
                    Iterator it = fileList.iterator();
                    while (it.hasNext()) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                        sftpFileName = entry.getFilename();
                    }
                }

                // 下载文件
                sftp.get(sftpFileName, outputStream);

                log.info("{} Download file success. TargetPath: {},Total time {}ms.",targetFileName, targetPath,System.currentTimeMillis()-start);

                return true;
            }else{
                log.info("sftp文件夹不存在");
                return false;
            }

        } catch (Exception e) {
            log.error("Download file failure. targetFileName: {}", targetFileName, e);
            throw new Exception(targetFileName+" Download File failure");

        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            // 关闭sftp
            sftpUtils.disconnect(sftp);
        }
    }


    /**
     *
     * @param sftpPath  sftp文件目录
     * @param localPath  本地存放文件目录
     * @param sftpFileName  sftp文件名
     * @param localFileName  本地文件名
     * @return
     * @throws Exception
     */
    @Override
    public boolean uploadFile(String sftpPath, String localPath, String sftpFileName, String localFileName) throws Exception {

        // 开启sftp连接
        ChannelSftp sftp = sftpUtils.createSftp();
        FileInputStream in = null;

        try {

            // 进入sftp文件目录
            sftp.cd(sftpPath);
            log.info("Change path to {}", sftpPath);

            File localFile = new File(localPath+localFileName);


            in = new FileInputStream(localFile);


            // 上传文件
            sftp.put(in, sftpFileName);

            log.info("upload file success. TargetPath: {}", sftpPath);

            return true;
        } catch (Exception e) {
            log.error("upload file failure. sftpPath: {}", sftpPath, e);
            throw new Exception("upload File failure");

        } finally {
            if (in != null) {
                in.close();
            }
            // 关闭sftp
            sftpUtils.disconnect(sftp);
        }
    }


    /**
     * 判断目录是否存在
     * @param directory
     * @return
     */
    public boolean isDirExist(String directory, ChannelSftp sftp)
    {
        boolean isDirExistFlag = false;
        try
        {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        }
        catch (Exception e)
        {
            if (e.getMessage().toLowerCase().equals("no such file"))
            {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

}

